package example.org;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;

import android.graphics.Bitmap;
import android.view.View;

import android.net.Uri;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ImageView;

import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;

public class EditImage extends Activity implements OnClickListener {
	private Button mOk;
	private String lemparan;
	private Uri imageFileUri;
	private ImageView chosenImageView;
	private static final int CROP_FROM_CAMERA = 2;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editpicture);

		chosenImageView = (ImageView) findViewById(R.id.imageView1);
		mOk = (Button) findViewById(R.id.button1);
		mOk.setOnClickListener(this);
		Bundle extrax = getIntent().getExtras();
		if (extrax != null) {
			lemparan = extrax.getString("gambar");
		}
		
		// SetBitmap
		try {
			// Tampilkan Gambar
			imageFileUri = Uri.parse(lemparan);
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageFileUri), null, bmpFactoryOptions);
			bmpFactoryOptions.inSampleSize = 2;
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageFileUri), null, bmpFactoryOptions);
			chosenImageView.setImageBitmap(bmp);
		} catch (FileNotFoundException e) {
			Log.v("ERROR", e.toString());
		}
		
		lemparan = null;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mOk) {
			chosenImageView.setDrawingCacheEnabled(true);
			chosenImageView.buildDrawingCache(true);
			Bitmap bitmap = chosenImageView.getDrawingCache();
			String path = Resource.savePath + "/"
					+ System.currentTimeMillis() + ".png";
			File file = new File(path);
			try {
				file.createNewFile();
				FileOutputStream ostream = new FileOutputStream(file);
				bitmap.compress(CompressFormat.PNG, 80, ostream);
				ostream.flush();
				ostream.close();
				imageFileUri = Uri.fromFile(file);
			} catch (Exception e) {
				e.printStackTrace();
			}

			Intent i = new Intent(this, ShareVia.class);
			i.putExtra("gambar", imageFileUri + "");
			startActivity(i);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			this.finish();
		}
		switch (requestCode) {
		case 1:
			imageFileUri = data.getData();
			doCrop();
			break;
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, "Rotatef");
		menu.add(1, 2, 0, "Blur");
		menu.add(1, 3, 0, "BlackWhite");
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Drawable d;
		Bitmap bmp;
		switch (item.getItemId()) {
		case 1:
			d = chosenImageView.getDrawable();
			bmp = ((BitmapDrawable) d).getBitmap();
			Bitmap bmpRotate = getRotateBitmap(bmp, 90);
			chosenImageView.setImageBitmap(bmpRotate);
			break;
		case 2:
			d = chosenImageView.getDrawable();
			bmp = ((BitmapDrawable) d).getBitmap();
			chosenImageView.setImageBitmap(blur(bmp));
			break;
		case 3:
			d = chosenImageView.getDrawable();
			bmp = ((BitmapDrawable) d).getBitmap();
			chosenImageView.setImageBitmap(blackAndWhite(bmp));
			break;
		case 4:
			break;
		}
		return true;
	}

	// Rotatef
	public Bitmap getRotateBitmap(Bitmap bm, int rotate) {
		int w = bm.getWidth();
		int h = bm.getHeight();
		Matrix mtx = new Matrix();
		mtx.postRotate(rotate);
		Bitmap rotateBMP = Bitmap.createBitmap(bm, 0, 0, w, h, mtx, true);
		return rotateBMP;
	}

	// Blur
	private Bitmap blur(Bitmap src) {
		int width = src.getWidth();
		int height = src.getHeight();

		BlurMaskFilter blurMaskFilter;
		Paint paintBlur = new Paint();

		Bitmap dest = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(dest);

		// Create background in White
		Bitmap alpha = src.extractAlpha();
		paintBlur.setColor(0xFFFFFFFF);
		canvas.drawBitmap(alpha, 0, 0, paintBlur);

		// Create outer blur, in White
		blurMaskFilter = new BlurMaskFilter(60, BlurMaskFilter.Blur.OUTER);
		paintBlur.setMaskFilter(blurMaskFilter);
		canvas.drawBitmap(alpha, 0, 0, paintBlur);

		// Create inner blur
		blurMaskFilter = new BlurMaskFilter(60, BlurMaskFilter.Blur.INNER);
		paintBlur.setMaskFilter(blurMaskFilter);
		canvas.drawBitmap(src, 0, 0, paintBlur);

		return dest;
	}

	// White And Black
	private Bitmap blackAndWhite(Bitmap src) {
		Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
				src.getConfig());
		for (int x = 0; x < src.getWidth(); x++) {
			for (int y =
					0; y < src.getHeight(); y++) {
				int pixelColor = src.getPixel(x, y);
				int pixelAlpha = Color.alpha(pixelColor);
				int pixelRed = Color.red(pixelColor);
				int pixelGreen = Color.green(pixelColor);
				int pixelBlue = Color.blue(pixelColor);

				int pixelBW = (pixelRed + pixelGreen + pixelBlue) / 3;
				int newPixel = Color
						.argb(pixelAlpha, pixelBW, pixelBW, pixelBW);

				dest.setPixel(x, y, newPixel);
			}
		}
		return dest;
	}

	// crop
	private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();

			return;
		} else {
			intent.setData(imageFileUri);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_FROM_CAMERA);
			} else {
				for (ResolveInfo res : list) {
					final CropOption co = new CropOption();

					co.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					co.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(co);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(
						getApplicationContext(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_FROM_CAMERA);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {

						if (imageFileUri != null) {
							getContentResolver().delete(imageFileUri, null,
									null);
							imageFileUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}
}